package zyj.example.demo.controller;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import zyj.example.demo.model.FileSystem;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("filesystem")
public class FileServerController {
    @Value("${itcast‐fastdfs.upload_location}")
    public String upload_location;

    @PostMapping("/upload")
    @ResponseBody
    public FileSystem upload(@RequestParam("file") MultipartFile file) throws IOException {
        //将文件先存储在web服务器上（本机），再调用fasdfs的client将文件上传到fastdfs服务器
        FileSystem fileSystem = new FileSystem();
        //得到文件的原始名称
        String originalFilename = file.getOriginalFilename();
        //文件扩展名
        String extention = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileNameNew = UUID.randomUUID() + extention;//防止重名
        //定义file，使用file存储上传的文件
        File file1 = new File(upload_location + fileNameNew);
        file.transferTo(file1);
        //获取新上传文件的物理路径
        String newFilePath = file1.getAbsolutePath();


        try {
            //加载fastDFS客户端的配置文件
            ClientGlobal.initByProperties("config/fastdfs-client.properties");
            System.out.println("network_timeout=" + ClientGlobal.g_network_timeout + "ms");
            System.out.println("charset=" + ClientGlobal.g_charset);

            //创建tracker的客户端
            TrackerClient tracker = new TrackerClient();
            TrackerServer trackerServer = tracker.getConnection();
            StorageServer storageServer = null;
            //定义storage的客户端
            StorageClient1 client = new StorageClient1(trackerServer, storageServer);
            //文件元信息
            NameValuePair[] metaList = new NameValuePair[1];
            metaList[0] = new NameValuePair("imageDogFile", originalFilename);
            //执行上传,将成功上传的存放再web服务器（本机）上的文件上传到fastdfs
            String fileId = client.upload_file1(newFilePath, extention, metaList);
            System.out.println("upload success. file id is: " + fileId);
            fileSystem.setFileId(fileId);
            fileSystem.setFilePath(fileId);
            fileSystem.setFileName(originalFilename);

            //通过调用service及dao将文件的路径存储到数据库中
            //..


            //关闭trackerServer的连接
            trackerServer.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return fileSystem;
    }


}
